﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace ChatTool
{
    public partial class FormChatToGroup : Form
    {
        private FormManager formManager;
        private Group group;
        private Point mouseDown;
        private DateTime startdateTime;
        public FormChatToGroup(FormManager formManager, Group group)
        {
            InitializeComponent();
            this.formManager = formManager;
            this.group = group;
            this.group.IsSelected = true;
            this.Text = group.Name;
            this.startdateTime = DateTime.Now;
        }

        private void FormChatToGroup_Load(object sender, EventArgs e)
        {
            //如何获得系统字体列表
            System.Drawing.Text.InstalledFontCollection fonts = new System.Drawing.Text.InstalledFontCollection();
            //System.Drawing.FontFamily initFamily;
            foreach (System.Drawing.FontFamily family in fonts.Families)
            {
                tscbFontFamily.Items.Add(family.Name);
            }
            tscbFontFamily.SelectedItem = "宋体";
            tscbFontSize.SelectedIndex = 3;

            this.formManager.NetManager.GroupMsgReceived += new NetManager.GroupMsgReceivedDelegate(NetManager_GroupMsgReceived);
            this.BackgroundImage = new Bitmap(this.formManager.BackgroundImage);
            this.labelName.Text = group.Name;
            this.labelMood.Text = group.GroupTheme;
            this.formManager.NetManager.GroupInfoReceived += new NetManager.GroupInfoReceivedDelegate(NetManager_GroupInfoReceived);
            Group group1 = new Group();
            group1.Name = group.Name;
            group1.Creator = group.Creator;
            group1.Requestor = NetManager.GetHostIP().ToString();
            group1.State = GroupState.CallUser;
            this.formManager.NetManager.StartBroadcastThread(group1);
        }

        private void NetManager_GroupMsgReceived(object obj)
        {
            GroupMsg msg = obj as GroupMsg;
            if (msg != null)
            {
                if (msg.GroupName == group.Name && msg.GroupCreator == group.Creator)
                {
                    string rtf = Tool.GetRtfString(msg.Sender + "  " + DateTime.Now.ToLongTimeString(), Tool.Font, Color.DarkGray);
                    AddRtfByClipboard(rtf);
                    AddRtfByClipboard(msg.SendRtf);
                }
            }
        }
        private delegate void AddRtfByClipboardDelegate(string rtf);
        //想聊天内容RichTextBox添加Rtf文本
        public void AddRtfByClipboard(string rtf)
        {
            if (rtbRecord.InvokeRequired)
            {
                AddRtfByClipboardDelegate d = AddRtfByClipboard;
                this.Invoke(d, rtf);
            }
            else
            {
                rtbRecord.ReadOnly = false;
                rtbRecord.AppendText(" ");
                rtbRecord.ScrollToCaret();
                Clipboard.SetData(DataFormats.Rtf, rtf);
                if (rtbRecord.CanPaste(DataFormats.GetFormat(DataFormats.Rtf)))
                {
                    rtbRecord.Paste(DataFormats.GetFormat(DataFormats.Rtf));
                }
                rtbRecord.AppendText(Environment.NewLine);//加这句代码是为了让下面的那句代码起作用
                rtbRecord.ScrollToCaret();
                rtbRecord.ReadOnly = true;
            }
        }
       
        private void NetManager_GroupInfoReceived(Group receiveGroup)
        {
            if (receiveGroup.State == GroupState.CallUser)
            {
                //MessageBox.Show("CallUser");
                if (receiveGroup.Name == "全局群组" && receiveGroup.Creator == "0.0.0.0")
                {
                    receiveGroup.State = GroupState.ReturnUser;
                    receiveGroup.User = this.formManager.UserOwn;
                    this.formManager.NetManager.StartBroadcastThread(receiveGroup);
                    //MessageBox.Show("CallUser1");
                }
                else if (OwnHaveJoinTheGroup(receiveGroup))
                {
                    receiveGroup.State = GroupState.ReturnUser;
                    receiveGroup.User = this.formManager.UserOwn;
                    this.formManager.NetManager.StartBroadcastThread(receiveGroup);
                    //MessageBox.Show("CallUser2");
                }
            }
            else if (receiveGroup.State == GroupState.ReturnUser)
            {
                //MessageBox.Show("ReturnUser");
                if (receiveGroup.Requestor == NetManager.GetHostIP().ToString())
                {
                    if (receiveGroup.Name == this.group.Name && receiveGroup.Creator == this.group.Creator)
                    {
                        this.AddOrDeleteMember("Add", receiveGroup.User);
                    }
                }
            }
        }

        private bool OwnHaveJoinTheGroup(Group receiveGroup)
        {
            List<Group> listGroup = FileOperate.GroupFromFile();
            if (listGroup != null)
            {
                foreach (Group item in listGroup)
                {
                    if (item.Name == receiveGroup.Name && item.Creator == receiveGroup.Creator)
                        return true;
                }
            }
            return false;
        }
        private delegate void AddOrDeleteMemberDelegate(string cmd, User user);
        private void AddOrDeleteMember(string cmd, User user)
        {
            if (tvMembers.InvokeRequired)
            {
                AddOrDeleteMemberDelegate d = AddOrDeleteMember;
                this.Invoke(d, cmd, user);
            }
            else
            {
                if (cmd == "Add")
                {
                    if (ContainUser(user) == false)
                    {
                        TreeNode node = new TreeNode(user.Name);
                        node.Tag = user;
                        this.tvMembers.Nodes.Add(node);
                    }
                }
            }
        }

        private bool ContainUser(User user)
        {
            foreach (TreeNode node in tvMembers.Nodes)
            {
                User user1 = node.Tag as User;
                if (user1.Name == user.Name && user1.Ip == user.Ip)
                    return true;
            }
            return false;
        }

        private void buttonMin_Click(object sender, EventArgs e)
        {
            Button but = sender as Button;
            string butName = but.Name;
            if (butName == "buttonClose")//关闭
            {
                if (Tool.peiZhiData.ContainsKey("SaveChatToGroupRecord") == false || Tool.peiZhiData["SaveChatToGroupRecord"] == "True")
                {
                    if (rtbRecord.Text.Trim() != "" && rtbRecord.Rtf != "")
                        FileOperate.WriteChatRecordToFile(group.Name + "@" + group.Creator, startdateTime, rtbRecord.Rtf);//保存聊天记录
                }
                this.Close();
            }
            else if (butName == "buttonMax")//最大化
            {
                if (this.WindowState == FormWindowState.Normal)
                    this.WindowState = FormWindowState.Maximized;
                else
                    this.WindowState = FormWindowState.Normal;
            }
            else if (butName == "buttonMin")//最小化
            {
                this.WindowState = FormWindowState.Minimized;
            }
        }

        private void panel2_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.mouseDown = e.Location;
            }
        }

        private void panel2_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                this.Left += (e.X - mouseDown.X);
                this.Top += (e.Y - mouseDown.Y);
            }
        }

        private void FormChatToGroup_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.group.IsSelected = false;
            this.formManager.NetManager.GroupInfoReceived -= new NetManager.GroupInfoReceivedDelegate(NetManager_GroupInfoReceived);
            this.formManager.NetManager.GroupMsgReceived -= new NetManager.GroupMsgReceivedDelegate(NetManager_GroupMsgReceived);
        }

        private void tsbSend_ButtonClick(object sender, EventArgs e)
        {
            if (rtbWrite.Text == "")
                return;
            try
            {
                //向自己的聊天内容框加聊天内容
                GroupMsg msg = new GroupMsg();
                msg.Sender = this.formManager.UserOwn.Name;
                msg.GroupName = group.Name;
                msg.GroupCreator = group.Creator;
                msg.SendRtf = rtbWrite.Rtf;
                if (this.formManager.NetManager.SendGroupMsg(msg) == false)
                {
                    MessageBox.Show("数据量太大,发送失败.");
                }

                this.rtbWrite.Clear();
                this.rtbWrite.Focus();

            }
            catch (Exception)
            {
                this.rtbWrite.Clear();
                this.rtbWrite.Focus();
            }
        }

        private void 截图时隐藏聊天窗口ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsm = sender as ToolStripMenuItem;
            string name = tsm.Name;
            if (name == "截图时隐藏聊天窗口ToolStripMenuItem")
            {
                tsm.Checked = !tsm.Checked;
            }
        }

        private void ttssbSendCutPicture_ButtonClick(object sender, EventArgs e)
        {
            if (截图时隐藏聊天窗口ToolStripMenuItem.Checked)
                this.Visible = false;
            new FormSetCopyRegion(this).Show();  
        }

        public void HandleBitmap(Bitmap bitmap)
        {
            Clipboard.SetImage(bitmap);//将表情图片放入系统剪贴板中
            if (Clipboard.ContainsImage())
            {
                if (rtbWrite.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap)))
                {
                    rtbWrite.Paste(DataFormats.GetFormat(DataFormats.Bitmap));//将剪贴板中的图片加入到发送面板中
                }
            }
            bitmap.Dispose();//释放原来的图片
            bitmap = null;
        }

        private void tsbSendPicture_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "(图像文件)*.jpg;*.jpeg;*.bmp;*.png;*.gif|*.jpg;*.jpeg;*.bmp;*.png;*.gif";
            openFileDialog.FileName = "选择图像文件";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    using (Stream stream = openFileDialog.OpenFile())
                    {
                        Bitmap sendImage = new Bitmap(stream);
                        HandleBitmap(sendImage);
                    }
                }
                catch (Exception ee)
                {
                    MessageBox.Show("发送图片时异常: " + ee.Message);
                }
            }
        }

        private void tsbSetFont_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            string name = tsb.Name;
            if (name == "tsbAddRough")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Bold;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbIncline")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Italic;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbUnderline")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Underline;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbStrikeout")
            {
                FontStyle style = rtbWrite.Font.Style ^ FontStyle.Strikeout;
                this.rtbWrite.Font = new Font(rtbWrite.Font.FontFamily.Name, rtbWrite.Font.Size, style);
            }
            else if (name == "tsbFontColor")
            {
                if (colorDialog.ShowDialog() == DialogResult.OK)
                    rtbWrite.ForeColor = colorDialog.Color;
            }
            else if (name == "tsbSetFont")
            {
                this.tsFont.Visible = !this.tsFont.Visible;
            }
           
        }

        private void tscbFontSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            string fontFamily = tscbFontFamily.SelectedItem.ToString();
            float fontSize = float.Parse(tscbFontSize.SelectedItem.ToString());
            this.rtbWrite.Font = new Font(fontFamily, fontSize, rtbWrite.Font.Style);
        }

        private void tscbFontFamily_SelectedIndexChanged(object sender, EventArgs e)
        {
            string fontFamily = tscbFontFamily.SelectedItem.ToString();
            float fontSize = 11.0F;
            if (tscbFontSize.SelectedItem != null)
                fontSize = float.Parse(tscbFontSize.SelectedItem.ToString());
            this.rtbWrite.Font = new Font(fontFamily, fontSize, rtbWrite.Font.Style);
        }
        private FormFace formFace;
        private void tsbFaceManager_Click(object sender, EventArgs e)
        {
            if (formFace == null)
            {
                formFace = new FormFace(this);
                formFace.Top = this.Top + this.tsMid.Top - formFace.Height + 90;
                formFace.Left = this.Left + 10;
                formFace.Show(this);
            }
            else
            {
                formFace.Top = this.Top + this.tsMid.Top - formFace.Height + 90;
                formFace.Left = this.Left + 10;
                formFace.Visible = !formFace.Visible;
            }
        }

        private void tsbSend_MouseEnter(object sender, EventArgs e)
        {
            this.Activate();
        }

        private void tsbClose_Click(object sender, EventArgs e)
        {
            this.rtbWrite.Clear();
            this.rtbWrite.Focus();
        }

        private void 按Enter发送消息ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //按Enter发送消息ToolStripMenuItem
            ToolStripMenuItem tsm = sender as ToolStripMenuItem;
            string name = tsm.Name;
            tsm.Checked = true;
            tsm.Enabled = false;
            if (name == "按Enter发送消息ToolStripMenuItem")
            {
                按CtrlEnter发送消息ToolStripMenuItem.Checked = false;
                按CtrlEnter发送消息ToolStripMenuItem.Enabled = true;
            }
            else
            {
                按Enter发送消息ToolStripMenuItem.Checked = false;
                按Enter发送消息ToolStripMenuItem.Enabled = true;
            }
        }

        private void rtbWrite_KeyDown(object sender, KeyEventArgs e)
        {
            if (this.按Enter发送消息ToolStripMenuItem.Checked == true)
            {
                if (e.Control == false && e.KeyCode == Keys.Enter)
                {
                    tsbSend.PerformButtonClick();
                    e.Handled = true;
                }
            }
            else
            {
                if (e.Control == true && e.KeyCode == Keys.Enter)
                {
                    tsbSend.PerformButtonClick();
                    e.Handled = true;
                }
            }
        }

        private void FormChatToGroup_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("FileNameW"))
            {
                e.Effect = DragDropEffects.Copy;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void FormChatToGroup_DragDrop(object sender, DragEventArgs e)
        {
            string[] fileNames = null;
            if (e.Data.GetDataPresent("FileNameW"))//判断拖放的对象中是不是有FileNameW格式的文件名
            {
                fileNames = (string[])e.Data.GetData("FileNameW");
            } 
            if (fileNames.Length > 0)
            {
                foreach (string fileName in fileNames)
                {
                    string format = fileName.Substring(fileName.LastIndexOf('.') + 1);//获取文件名的格式后缀
                    if (format.Equals("gif", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("jpg", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("jpeg", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("bmp", StringComparison.CurrentCultureIgnoreCase)
                        || format.Equals("png", StringComparison.CurrentCultureIgnoreCase))
                    {
                        Image image = Image.FromFile(fileName);
                        Clipboard.SetImage(image);
                        if (Clipboard.ContainsImage())
                        {
                            if (rtbWrite.CanPaste(DataFormats.GetFormat(DataFormats.Bitmap)))
                            {
                                rtbWrite.Paste(DataFormats.GetFormat(DataFormats.Bitmap));
                            }
                        }
                        image.Dispose();//释放原来的图片对象
                        image = null;
                    }
                  
                }
            }
        }

        private void tsbMsgRecord_Click(object sender, EventArgs e)
        {
            FormChatRecordManager formChatRecordManager = new FormChatRecordManager(group.Name + "@" + group.Creator);
            formChatRecordManager.Show();
        }
    }
}
